package com.data.csv;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import tool.ClientTool;
import tool.HtmlTool;
import tool.JsonTool;
import tool.TimeTool;
import tool.encrypt.IdentifyTool;

import com.admin.bean.ActvOrDaka;
import com.base.bean.*;
import com.base.dao.*;
import com.base.domain.*;
import com.base.service.*;

/**
 * GPS打卡以及行动的数据导出

判定结果：
0 待审
1 通过
2 无效
3 重复
4 其他

行动类型：
0:"", 
1～3:"空白市场开发", "二级渠道开发", "新客户拜访", 
4～6:"老客户拜访","商务谈判", "交机", 
7～9:"备注其他", "客户催款","电话拜访"

 * @author chz
 * 
 */
public class ActvtDeal {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Map<Integer,User> usermap;

	private List<ActvtDetail> actvtDetailList;
	private List<DakaDetail> dakaDetailList;
	private Integer resultState;
	private TCheck tCheck;

	private String SUCCESS = "success";
	private String ERROR = "error";

	private Integer id; // 行动或打卡记录id
	private Integer type; // 0：查询当日记录 1：审核后再查询当日记录
	private Integer checked; // 审核结果 0 默认 1：有效 21：无效I（不清楚 ） 22：无效II（不规范
								// ）23：无效（重复或作废） 3：不确定 4：系统故障
	private String checkmemo, tip;

	private String date; // 查询日期(-为分割线)
	private String jsonData;
	private String provinceId;
	private String company;

	// 辅助类
	private GpsCheckService gcs; // can get TCheckDao
	private DakaService dks;
	private ActivityService as;
	private UserService us;

	
	
	static String[] actvType = { "", "空白市场开发", "二级渠道开发", "新客户拜访", "老客户拜访",
			"商务谈判", "交机", "备注其他", "客户催款","电话拜访","小挖开发","电话催收" };
	
	//获取某月的行动以及打卡的数据
	public static void main(String[] args){
		ActvtDeal gd = new ActvtDeal();
//		gd.writeCSV("/Users/chz/Desktop/actvt_4.csv",2016,4,true);	//获取某月以后的行动的数据
		gd.writeCSV("/Users/chz/Desktop/actvt_8.csv",2016,8,false);	//获取某月的行动的数据

	}

	public ActvtDeal() {
		// TODO Auto-generated constructor stub
		gcs = GpsCheckService.getInstance();
		dks = DakaService.getInstance();
		as = ActivityService.getInstance();
		us = UserService.getInstance();
		this.getUserMap();
	}

//	@Deprecated
//	public void genResult(){
//		DakaResultDao rDao = (DakaResultDao) _BaseDao.ac.getBean("DakaResultDao");
//		
//		List<ActvOrDaka>  list  = this.getActvOrDakaList(2016, 4);
//		
//		// 016-04-01 02:50:50
//		
//		
//		for(ActvOrDaka data:list){
//			if(data.getType()==2)	//行动数据跳过
//				continue;
//			DakaResult r = new DakaResult();
//			
//			
//			Calendar calendar = TimeTool.convertCal(data.getTime());
////			System.out.println(data.getTime());
//			
//			int year = calendar.get(1);
//			int month = calendar.get(2)+1;
//			int date = calendar.get(5);
//			int hour = calendar.get(11);
//			int minute = calendar.get(12);
//			int weekDay = calendar.get(7);
//			
////			System.out.println(calendar.YEAR);
////			System.out.println(calendar.MONTH);
////			System.out.println(calendar.DATE);
////			System.out.println(calendar.DAY_OF_WEEK);
////			System.out.println(calendar.HOUR_OF_DAY);
//			
//			r.setWeekOfDay(weekDay);
//			r.setYear(year);
//			r.setMonth(month);
//			r.setDate(date);
//			r.setHour(hour);
//			r.setMinute(minute);
//			r.setDkId(data.getId());
//			r.setUid(data.getUid());
//			r.setTime(data.getTime());
////			r.setChecked(data.gets)
////			System.out.println(data.getUid());
//
//			if(hour <=12){
//				r.setState(1);
//			}
//			else if (hour >12){
//				r.setState(2);
//			}
//			else{
//				r.setState(3);
//			}
//			r.setProvince(data.getProvince());
//			r.setCompany(data.getDep());
//			rDao.merge(r);
//			
//		}
//		
//	}
	
	
	
	public void writeCSV(String filePath,int year,int month,boolean toNow){
		
		List<String> list =  new ArrayList<String>();
		list.add(ActvOrDaka.getTitle());
		List<ActvOrDaka> dataList = this.getActvOrDakaList(year,month,toNow);
		for(ActvOrDaka data:dataList){
			list.add(data.toString());
		}
		
		tool.CSVUtils.exportCsv(new File(filePath), list);
	}
	
	
	
	
	public List<ActvOrDaka> getActvOrDakaList(int year ,int month,boolean toNow) {
		 List<ActvOrDaka> dataList = new ArrayList<ActvOrDaka>();

		 if(!toNow)
			 this.actvtDetailList = this.convertByActvtList(this.getXdList(year, month));
		 else
			 this.actvtDetailList = this.convertByActvtList(this.getXdList(year, month,true));

		if (this.actvtDetailList != null) {
			for (ActvtDetail ad : this.actvtDetailList) {
				ActvOrDaka data = new ActvOrDaka();
				data.setId(ad.getActivity().getAid());

				Integer _checked = ad.getActivity().getChecked();
				_checked = (_checked == null ? 0 : _checked);
				data.setState(_checked);
				data.setUid(ad.getUser().getUid());
				data.setType(2);
				data.setName(ad.getUser().getTruename());
				data.setDep(ad.getUser().getCompany());
				data.setProvince(ad.getUser().getProvince());
				data.setCity(ad.getUser().getCity());
				data.setAddress(ad.getActivity().getAddress());
				data.setPhoto(ad.getActivity().getPhotoName());
				data.setTime(ad.getActivity().getCreated());
				data.setPath(ad.getActivity().getPath());
				data.setActvType(ad.getActivity().getType()); // 行动类型
				
				
				// data.setClientCode("CN_"+new
				// Integer(ad.getActivity().getCid()*2+3).toString());
				data.setClientCode(IdentifyTool.enCodeCid(ad.getActivity()
						.getCid()));
				
				data.setClientName(ad.getActivity().getClientName());

				Integer it = ad.getActivity().getType();
				it = (it == null ? 0 : it);
				String content = ad.getActivity().getContent();
				content = (content == null ? "" : content);
				String _type = this.actvType[it];
				data.setMemo(content);

				if (ad.getActivity().getCheckmemo() != null)
					data.setCheckmemo(ad.getActivity().getCheckmemo());
				else
					data.setCheckmemo("");

				dataList.add(data);

			}

		}

		// System.out.println(this.jsonData);

		return dataList;

	}

	private  void getUserMap(){
		Map<Integer,User> map = new HashMap();
		List<User> users = UserService.getInstance().getUserDao().findByHql("from User");
		for(User u:users){
			map.put(u.getUid(), u);
		}
		this.usermap=map;
		
	}
	
	
	/*
	 * 
	 * Transaction tx = session.beginTransaction();
	 * 
	 * Query query = session.createQuery(hql) .setTimestamp("beforeTime", _time)
	 * .setInteger("uid",uid) .setInteger("category", category)
	 * .setFirstResult(offset) .setMaxResults(pageSize);
	 * 
	 * List results = query.list(); tx.commit(); return results;
	 */
	// 获取某月打卡的数据
	private List<UserDaka> getDkList(int year, int month) {
		String hql = "from UserDaka where checked=1 and created > :start and created < :end";
		Timestamp start = TimeTool.generateTime(year, month, 1);
		Timestamp end = TimeTool.generateTime(year, month+1, 1);
		Session session = this.dks.getDkDao().getSessionFactory()
				.getCurrentSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery(hql).setTimestamp("start", start)
				.setTimestamp("end", end);

		List results = query.list();
		tx.commit();
		return results;
	}

	// 获取某月行动的数据
	private List<Activity> getXdList(int year, int month) {
		String hql = "from Activity where created > :start and created < :end";
		Timestamp start = TimeTool.generateTime(year, month, 1);
		Timestamp end = TimeTool.generateTime(year, month+1, 1);
		Session session = this.as.getActvtDao().getSessionFactory()
				.getCurrentSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery(hql).setTimestamp("start", start)
				.setTimestamp("end", end);

		List results = query.list();
		tx.commit();
		return results;
	}
	
	// 获取某月以后行动的数据
		private List<Activity> getXdList(int year, int month,boolean toNow) {
			String hql = "from Activity where created > :start ";
			Timestamp start = TimeTool.generateTime(year, month, 1);
			Session session = this.as.getActvtDao().getSessionFactory()
					.getCurrentSession();
			Transaction tx = session.beginTransaction();
			Query query = session.createQuery(hql).setTimestamp("start", start);

			List results = query.list();
			tx.commit();
			return results;
		}
	

	// 行动转化为ActvtDetial
	private List<ActvtDetail> convertByActvtList(List<Activity> acvts) {
		List<ActvtDetail> list = new ArrayList<ActvtDetail>();
		try {
			for (Activity a : acvts) {
				ActvtDetail ad = new ActvtDetail();
				ad.setActivity(a);
				try {
					ad.setUser(usermap.get(a.getCreator()));
//					ad.setUser(us
//							.getUserDao()
//							.findByHql(
//									"from User u where u.uid=" + a.getCreator())
//							.get(0));
					list.add(ad);
				} catch (Exception e) { // 未找到用户则跳过
					continue;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}

	// 打卡转化为DakaDetail
	private List<DakaDetail> convertByDakaList(List<UserDaka> dks) {
		List<DakaDetail> list = new ArrayList<DakaDetail>();
		try {
			for (UserDaka dk : dks) {
				DakaDetail dd = new DakaDetail();
				dd.setUserDaka(dk);
				try {
					dd.setUser(usermap.get(dk.getUid()));
					
//					dd.setUser(us
//							.getUserDao()
//							.findByHql("from User u where u.uid=" + dk.getUid())
//							.get(0));
					list.add(dd);
				} catch (Exception e) { // 未找到用户则跳过
					continue;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}

	

	public List<ActvtDetail> getActvtDetailList() {
		return actvtDetailList;
	}

	public void setActvtDetailList(List<ActvtDetail> actvtDetailList) {
		this.actvtDetailList = actvtDetailList;
	}

	public List<DakaDetail> getDakaDetailList() {
		return dakaDetailList;
	}

	public void setDakaDetailList(List<DakaDetail> dakaDetailList) {
		this.dakaDetailList = dakaDetailList;
	}

	

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getType() {
		return type;
	}

	public void setType(Integer type) {
		this.type = type;
	}

	public Integer getChecked() {
		return checked;
	}

	public void setChecked(Integer checked) {
		this.checked = checked;
	}

	public String getCheckmemo() {
		return checkmemo;
	}

	public void setCheckmemo(String checkmemo) {
		this.checkmemo = checkmemo;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getJsonData() {
		return jsonData;
	}

	public void setJsonData(String jsonData) {
		this.jsonData = jsonData;
	}

	public Integer getResultState() {
		return resultState;
	}

	public void setResultState(Integer resultState) {
		this.resultState = resultState;
	}

	public TCheck gettCheck() {
		return tCheck;
	}

	public void settCheck(TCheck tCheck) {
		this.tCheck = tCheck;
	}

	public String getProvinceId() {
		return provinceId;
	}

	public void setProvinceId(String provinceId) {
		this.provinceId = provinceId;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public String getTip() {
		return tip;
	}

	public void setTip(String tip) {
		this.tip = tip;
	}

}
